package cn.sail.qf.swagger.config;

import cn.sail.qf.swagger.properties.SwaggerProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * 自动装配类
 * 加载配置文件到属性类对象
 * 实例化 Swagger运行所需要的对象
 *
 * @EnableConfigurationProperties 开启配置文件读取
 * @ConditionalOnProperty 按照配置文件中定义的属性值类判断是否启用当前自动装配类
 * 例子：
 *      cawbutler:
 *        swagger:
 *          enabled: true
 *          true:生效 false：不生效
 */
@Configuration
@EnableConfigurationProperties(SwaggerProperties.class)
@ConditionalOnProperty(prefix = "sail.swagger", value = "isOpen",havingValue = "true")
public class SwaggerAutoConfiguration {

    @Autowired
    private SwaggerProperties swaggerProperties;

    @Bean
    public Docket createRestApi() {
        System.out.println("swagger-start");
        Assert.notNull(swaggerProperties.getApiBasePackage(), "must set application.yml -> sail.swagger.api-base-package");

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())//这个方法的作用（生成接口的时候页面显示的信息）
                .select()//表示的是选择哪些路径和API生成文档
                .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getApiBasePackage()))//告诉他要扫描的接口存在的这个包
                .paths(PathSelectors.any())//对所有的API进行监控
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDescription())
                .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl())//更新服务条款url
                .version(swaggerProperties.getVersion())
                .build();
    }
}
